package com.ug.common.utils;

import cn.hutool.core.util.ObjectUtil;
import com.ug.common.constant.CommonConstants;
import com.ug.system.entity.properties.SocialLoginConfigProperties;
import com.ug.system.entity.properties.SocialProperties;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;

/**
 * @Author: LY
 * @Date: 2024/9/18 14:32
 * @Description: 认证授权工具类 JustAuth
 * 文档地址：https://www.justauth.cn/guide/oauth/gitee/#_3-%E6%8E%88%E6%9D%83%E7%BB%93%E6%9E%9C
 */
public class SocialUtils {

    @SuppressWarnings("unchecked")
    public static AuthResponse<AuthUser> loginAuth(String source, String code, String state, SocialProperties socialProperties) throws AuthException {
        AuthRequest authRequest = getAuthRequest(source, socialProperties);
        AuthCallback callback = new AuthCallback();
        callback.setCode(code);
        callback.setState(state);
        return authRequest.login(callback);
    }

    /**
     * 生成JustAuth第三方授权链接
     * @param source 来源
     * @param socialProperties 配置文件信息
     * @throws AuthException 异常信息
     */
    public static AuthRequest getAuthRequest(String source, SocialProperties socialProperties) throws AuthException {
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
        if (ObjectUtil.isNull(obj)) {
            throw new AuthException("不支持的第三方登录类型");
        }
        AuthConfig.AuthConfigBuilder builder = AuthConfig.builder()
                .clientId(obj.getClientId())
                .clientSecret(obj.getClientSecret())
                .redirectUri(obj.getRedirectUri())
                .scopes(obj.getScopes());
        return switch (source.toLowerCase()) {
            case CommonConstants.LOGIN_TYPE_GITEE -> new AuthGiteeRequest(builder.build());
            default -> throw new AuthException("未获取到有效的Auth配置");
        };
    }
}
